package com.mycompany.service;

import java.io.Serializable;

import org.springframework.transaction.annotation.Transactional;

import com.mycompany.dao.CommonDao;
import com.mycompany.entity.BaseEntity;
import com.mycompany.exception.ApplicationRuntimeException;

@Transactional
public abstract class DefaultCommonService<I extends Serializable, T extends BaseEntity<I>>
		implements CommonService<I, T> {
	private static final String ERROR_MSG_MISSING_PK = "empty pk for teacher, can processing";
	private static final String ERROR_MSG_ENTITY_ALREADY_EXISTS = "entity already exists";

	protected abstract CommonDao<I, T> getDao();

	@Override
	@Transactional(readOnly = true)
	public T getById(I id) {
		return getDao().getById(id);
	}

	@Override
	public void delete(T entity) {
		if (entity.getId() == null) {
			throw new ApplicationRuntimeException(ERROR_MSG_MISSING_PK);
		}
		getDao().delete(entity);
	}

	@Override
	public void insert(T entity) {
		if (entity.getId() != null) {
			throw new ApplicationRuntimeException(
					ERROR_MSG_ENTITY_ALREADY_EXISTS);
		}
		getDao().insert(entity);
	}

	@Override
	public void saveOrUpdate(T entity) {
		if (entity.getId() == null) {
			insert(entity);
		} else {
			update(entity);
		}
	}

	@Override
	public void update(T entity) {
		if (entity.getId() == null) {
			throw new ApplicationRuntimeException(ERROR_MSG_MISSING_PK);
		}
		getDao().update(entity);
	}
	
	@Override
	public void deleteAll() {
		getDao().deleteAll();
	}

}
